package com.cmge.ad.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.cmge.ad.mapper.PictureMapper;
import com.cmge.ad.model.Album;
import com.cmge.ad.model.AlbumStore;
import com.cmge.ad.model.Menu;
import com.cmge.ad.model.Picture;
import com.cmge.ad.service.PictureService;
import com.cmge.ad.util.FileUtil;
import com.cmge.ad.util.Pager;
import com.cmge.ad.util.SuprUtil;
import com.cmge.ad.util.context.ServletContextUtil;

@Service
@Transactional(isolation=Isolation.DEFAULT,rollbackFor=Exception.class)
public class PictureServiceImpl implements PictureService{
	
	public static final Logger logger = Logger.getLogger(PictureServiceImpl.class);
	
	@Autowired
	private PictureMapper pictureMapper;
	
	@Override
	public void getPictureStoreList(Pager<AlbumStore> pager, HashMap<String, Object> paramMap) {
		int count = pictureMapper.getPictureStoreCount(paramMap);
		pager.setTotalCount(count);
		if(count > 0){
			paramMap.put("start", pager.getStart());
			paramMap.put("limit", pager.getLimit());
			List<AlbumStore> appList = pictureMapper.getPictureStoreList(paramMap);
			if(!SuprUtil.isEmptyCollection(appList)){
				for(AlbumStore as : appList){
					// 根据相册查询一个图片作为封面图
					List<Picture> picList = pictureMapper.getPictureStoreInfoList(String.valueOf(as.getId()));
					String url = "";
					for(int i = 0;i<(picList.size() > 5 ? 5 : picList.size());i++){
						url += picList.get(i).getMinImageUrl() +";";
					}
					as.setAlbumUrl(url);
				}
			}
			pager.setRows(appList);
		}
	}
	
	@Override
	public List<Picture> getPictureStoreList(String id) {
		return pictureMapper.getPictureStoreInfoList(id);
	}
	
	@Override
	public void getPictureList(Pager<Album> pager, HashMap<String, Object> paramMap) {
		int count = pictureMapper.getPictureCount(paramMap);
		pager.setTotalCount(count);
		if(count > 0){
			paramMap.put("start", pager.getStart());
			paramMap.put("limit", pager.getLimit());
			List<Album> appList = pictureMapper.getPictureList(paramMap);
			pager.setRows(appList);
		}
	}
	
	@Override
	public AlbumStore getPictureStoreInfoById(String id) {
		return pictureMapper.getPictureStoreInfoById(id);
	}
	
	@Override
	public Album getPictureInfoById(String id) {
		return pictureMapper.getPictureInfoById(id);
	}
	
	@Override
	public List<Picture> getPictureList(String id) {
		return pictureMapper.getPictureList(id);
	}
	
	@Override
	public List<Menu> getPictureChildMenu() {
		return pictureMapper.getPictureChildMenu();
	}
	
	@Override
	public String getPictureStoreId(AlbumStore album) {
		return pictureMapper.getPictureStoreId(album);
	}
	
	@Override
	public String getPictureId(Album album) {
		return pictureMapper.getPictureId(album);
	}
	
	@Override
	public void deletePictureStoreById(Integer id) {
		pictureMapper.deletePictureStoreById(id);
		pictureMapper.deletePictureStoreInfoById(id);
	}
	
	@Override
	public boolean existSyncPicture(Integer id) {
		int count = pictureMapper.existSyncPicture(id);
		return count > 0 ? true : false;
	}
	
	@Override
	public void syncPictureStore(Integer id, Integer menuId) {
		HashMap<String,Object> param = new HashMap<String,Object>();
		param.put("id", id);
		param.put("menuId", menuId);
		pictureMapper.syncPictureStore(param);
		pictureMapper.syncPictureStoreStatue(id);
	}
	
	@Override
	public List<AlbumStore> getSyncAlbumList() {
		return pictureMapper.getSyncAlbumList();
	}
	
	@Override
	public void deleteSyncAlbum(AlbumStore album) {
		pictureMapper.deleteSyncAlbum(album);
	}
	
	@Override
	public void updatePictureStoreStatue(AlbumStore album) {
		pictureMapper.updatePictureStoreStatue(album);
	}
	
	@Override
	public List<Picture> getPictureListByAlbumId(Integer id) {
		return pictureMapper.getPictureListByAlbumId(id);
	}
	
	@Override
	public List<Picture> getPictureListById(String id) {
		return pictureMapper.getPictureListById(id);
	}
	
	@Override
	public void addAlbum(AlbumStore album) {
		pictureMapper.addAlbum(album);
	}
	
	@Override
	public void addPicture(Picture pic) {
		pictureMapper.addPicture(pic);
	}
	
	@Override
	public void syncAlbum() {
		List<AlbumStore> list = getSyncAlbumList();
		
		logger.info("待同步的相册数量："+(list != null ? list.size() : 0));
		
		// 获取待同步的相册
		if(!SuprUtil.isEmptyCollection(list)){
			// 遍历相册
			for(AlbumStore album : list){
				int storeId = album.getId();
				try {
					// 获取相册的图片
					List<Picture> picList = getPictureListByAlbumId(album.getId());
					if(!SuprUtil.isEmptyCollection(picList)){
						// 赞
						album.setZan(new Random().nextInt(1000));
						// 同步相册到album中
						addAlbum(album);
						for(Picture pic : picList){
							int width = 0,hight = 0;
							String locationUrl = "";
							String fileName = ServletContextUtil.getContext().getRealPath("/")+"upload/";
							String file = pic.getMinImageUrl();
							int index = file.toLowerCase().lastIndexOf(".jpg");
							
							if(index < 0){
								index = file.toLowerCase().lastIndexOf(".png");
							}
							
							String pref = "";
							
							if(index < 0){
								pref = ".jpg";
							}else{
								pref = file.substring(index, file.length());
							}
							
							String post = System.currentTimeMillis() + pref;
							fileName = fileName + post;
							
							FileUtil.downloadFile(pic.getMinImageUrl(),fileName);
							
							File picture = new File(fileName);  
					        BufferedImage sourceImg =ImageIO.read(new FileInputStream(picture));   
							width = sourceImg.getWidth();
							hight = sourceImg.getHeight();
							
							locationUrl = "/upload/"+post;
							
							pic.setAlbumId(album.getId());
							pic.setWidth(width);
							pic.setHeight(hight);
							pic.setLocationUrl(locationUrl);
							
							// 同步相片到picture
							addPicture(pic);
						}
						
						// 更新仓库相册的状态  已同步
						album.setId(storeId);
						album.setStatue(1);
						updatePictureStoreStatue(album);
					}else{
						// 更新仓库相册的状态  同步失败
						album.setStatue(2);
						updatePictureStoreStatue(album);
					}
				} catch (Exception e) {
					logger.error("同步相册异常：【"+album.getId()+"】",e);
					// 更新仓库相册的状态  同步失败
					album.setId(storeId);
					album.setStatue(2);
					updatePictureStoreStatue(album);
				} finally{
					// 从临时表中删除相册
					deleteSyncAlbum(album);
					logger.info("同步完成一个相册．．．");
				}
			}
		}
	}
	
	@Override
	public List<Menu> getAllPictureMenu() {
		return pictureMapper.getAllPictureMenu();
	}
	
}
